/**
 * Http请求封装工具类
 * Axios是基于http客户端的promise，面向浏览器和NodeJS
 */
import axios from 'axios';
import qs from 'qs';
import config from '../config';
import _ from 'lodash';

axios.defaults.withCredentials = true;

const initHttp = function(module) {
  let options = Object.assign({}, config.axiosConfig['default']);
  if (module) {
    options.baseURL = config.axiosConfig[module].baseURL;
    console.log(options.baseURL);
  }
  let axiosInstant = axios.create(options);
  axiosInstant.all = axios.all;
  axiosInstant.spread = axios.spread;

  /**
   * 添加一个请求拦截器
   */
  axiosInstant.interceptors.request.use(function(config) {
    if (_.isObject(config.data)) {
      let params = qs.stringify({parameter: JSON.stringify(config.data)});
      config.data = params;
    }
    config.headers.requestId = new Date().getTime();
    return config;
  }, function(error) {
    console.log('请求失败,原因：' + error);
  });

  /**
   * 添加一个返回拦截器
   */
  axiosInstant.interceptors.response.use(function(response, b) {
    //兼容Excel文件下载  返回response对象
    if (response.headers &&
      (response.headers['content-type'].indexOf('application/vnd.ms-excel') >
        -1 ||
        response.headers['content-type'].indexOf('APPLICATION/OCTET-STREAM') >
        -1)) {
      return response;
    }
    response.data.success = response.data.code === 200;
    if (!response.data.success) {
      console.log('业务请求失败，地址：' + response.config.url);
      console.log('原因：' + response.data.message);
      console.log(response.data.error);
      return Promise.reject(response.data.message);
    }
    let data = response.data.data;
    response.data = data;
    return response;
  }, function(error) {
    console.log('http请求失败，地址：' + error.config.url);
    console.log('原因：' + error);
    return Promise.reject('http请求失败（' + error + ')');
  });

  /**
   * 封装post调用
   *
   * @param url 请求路径
   * @param param 参数对象
   * @param reback 正确处理函数
   * @param catchReback 错误处理函数
   */
  axiosInstant.postH = function(url, param, reback, catchReback) {
    return this.post(url, qs.stringify(param))
      .then(
        m => {
          let data = m;
          return reback(data);
        }
      )
      .catch(function(error) {
        if (typeof catchReback === 'function') {
          catchReback(error);
        }
      });
  };

  /**
   * 封装post调用 增加 responseType: 'blob'
   *
   * @param url 请求路径
   * @param param 参数对象
   * @param reback 正确处理函数
   * @param catchReback 错误处理函数
   */
  axiosInstant.postD = function(url, param, reback, catchReback) {
    this.post(url, qs.stringify({parameter: JSON.stringify(param)}),
      {responseType: 'blob'}).then(
      m => {
        let data = m;
        reback(data);
      }
    ).catch(function(error) {
      if (typeof catchReback === 'function') {
        catchReback(error);
      }
    });
  };

  return axiosInstant;
};

export default initHttp;


